<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">活动</el-breadcrumb-item>
      <el-breadcrumb-item>广告列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--查询表单-->
    <el-form label-width="200px" :inline="true" :model="searchMap" class="demo-form-inline">

        <el-form-item label-width="260px" label="广告编号">
            <el-input v-model="searchMap.id" placeholder="请输入广告编号"></el-input>
        </el-form-item>

        <el-form-item label-width="100px" label="广告名称">
            <el-input v-model="searchMap.name" placeholder="请输入广告名称"></el-input>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <!-- <el-button type="primary" @click="dialogFormVisible=true; adForm={}; imageUrl=''">新增广告</el-button> -->
          <!-- <el-button icon="el-icon-folder-add" style="float: right"  @click="dialogFormVisible=true; adForm={}; imageUrl=''">添加广告</el-button> -->
        </el-form-item>
    </el-form>


<!--新增或修改对话框-->
<el-dialog :title="adForm.id==null?'新增广告':'编辑广告'" :visible.sync="dialogFormVisible">
  <el-form :model="adForm">

    <el-form-item label="广告名称" :label-width="formLabelWidth">
      <el-input v-model="adForm.name" autocomplete="off"></el-input>
    </el-form-item>

    <el-form-item label="广告位置" :label-width="formLabelWidth">
        <el-select v-model="adForm.position" placeholder="请选择">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
    </el-form-item>

    <el-form-item label="广告图片" :label-width="formLabelWidth">
      <!--上传文件组件-->
          <!-- <SingleUpload v-model="adForm.image"></SingleUpload> -->
        <!-- action="http://myqingchengdemo.oss-cn-shanghai.aliyuncs.com" -->
      <el-upload
        action="http://localhost:88/api/business/upload/oss?folder=Business_images"
        class="avatar-uploader"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>

    <el-form-item label="广告状态" :label-width="formLabelWidth">
          <el-switch
            v-model="adForm.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="1"
            inactive-value="0">
          </el-switch>
    </el-form-item>

   <el-form-item label="广告开始时间" :label-width="formLabelWidth">
          <div class="block">
    <el-date-picker
      v-model="adForm.startTime"
      type="datetime"
      placeholder="选择开始日期时间">
    </el-date-picker>
  </div>
      </el-form-item>

   <el-form-item label="广告结束时间" :label-width="formLabelWidth">
  <div class="block">
    <el-date-picker
      v-model="adForm.endTime"
      type="datetime"
      placeholder="选择到期日期时间">
    </el-date-picker>
  </div>
        </el-form-item>


   <el-form-item label="广告备注内容" :label-width="formLabelWidth">
        <el-input
  type="textarea"
  :rows="2"
  placeholder="请输入备注内容"
  v-model="adForm.remarks">
</el-input>
        </el-form-item>

  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible = false;">取 消</el-button>
    <el-button type="primary" @click="save">确 定</el-button>
  </div>
</el-dialog>

    <!--数据表格-->
    <el-table
    :data="tableData"
    style="width: 100%">
    <el-table-column
      label="编号"
      width="60" prop="id">
    </el-table-column>
    <el-table-column
      label="广告名称"
      width="100" prop="name">
    </el-table-column>
    <el-table-column
      label="广告位置"
      width="130" prop="position">
    </el-table-column>
    <el-table-column
      label="广告图片"
      width="200">
       <template slot-scope="scope">
         <img :src="scope.row.image" width="160px" height="80px">
       </template>
    </el-table-column>
    <el-table-column
      label="开始时间"
      width="180" prop="startTime">
      </el-table-column>
    <el-table-column
      label="结束时间"
      width="180" prop="endTime">
    </el-table-column>
      <el-table-column label="下线/上线" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="1"
            inactive-value="0"
            @change="changeSwitchStatus(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
    <el-table-column
      label="备注"
      width="180" prop="remarks">
    </el-table-column>
    <el-table-column label="操作" width="180">
      <template slot-scope="scope">
        <el-row>
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" circle
              @click="handleEdit(scope.$index, scope.row)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" circle
              @click="handleDelete(scope.$index, scope.row)"></el-button>
          </el-row>
      </template>
    </el-table-column>
  </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="pageSizeList"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      align="center">
    </el-pagination>
    </div>
</template>

<script>
//图片上传组件引用
// import SingleUpload from '../../components/upload/singleUpload'

export default {
     data () {
      return {
        // 呈现数据
        tableData: [],
        // 当前页码
        currentPage: 1,
        // 页大小
        pageSize: 4,
        // 页大小列表
        pageSizeList: [4, 10, 20, 50, 100],
        // 总记录数
        total: 0,
        // 查询表单对象
        searchMap: {},
        // 控制对话框是否显示的标志
        dialogFormVisible: false,
        // 绑定表单对象
        adForm: {},
        // 表单label的宽度
        formLabelWidth: '120px',
        //广告位
        options: [{
          value: 'web_index_lb',
          label: '首页广告位'
        }, {
          value: 'index_ea_lb',
          label: '家用电器广告位'
        }, {
          value: 'index_mobile_lb ',
          label: '手机通讯广告位'
        }],
        // 映射上传文件组件对应的文件路径
        imageUrl: ''
      }
    },
    methods: {
      //时间转换
    // dateFormat(row,column,cellValue){
    //   return cellValue ? fecha.format (new Date(cellValue),'yyyy-MM-dd HH:mm:ss') : ''
    // },

      // switch改变事件
    async changeSwitchStatus (row) {
      // console.log(row.status)
      // 发请求
        const { data: res } = await this.$http.post(`/business/ad/update`,row)
        if (res.code === 200 && row.status==1) {
            this.$message({
              type: 'success',
              message: '上线成功!'
            })
            // 刷新页面
            this.getBrandList()
        }else if (res.code === 200 && row.status==0) {
            this.$message({
              type: 'success',
              message: '下线成功!'
            })
            // 刷新页面
            this.getBrandList()
        }
    },
      // 新增或编辑对话框的确认按钮，即保存
      async save () {
        this.adForm.image = this.imageUrl
        this.dialogFormVisible = false
        // 发请求
        const { data: res } = await this.$http.post(`/business/ad/${this.adForm.id == null ? 'add' : 'update'}`, this.adForm)
        if (res.code === 200 && this.adForm.id==null) {
            this.$message({
              type: 'success',
              message: '添加广告成功!'
            })
            // 刷新页面
            this.getBrandList()
        }else{
          this.$message({
              type: 'success',
              message: '修改广告成功!'
            })
            // 刷新页面
            this.getBrandList()
        }
      },
      // 获取广告信息列表
      async getBrandList () {
        // 发送请求查询数据并返回
        const { data: res } = await this.$http.post(`/business/ad/findPage?page=${this.currentPage}&size=${this.pageSize}`, this.searchMap)
        this.tableData = res.rows
        this.total = res.total
      },
      // 查询按钮
      onSubmit () {
        this.getBrandList()
      },
      // 编辑按钮
      async handleEdit (index, row) { 
        this.dialogFormVisible = true
        // const id = row.id
        // 发送请求
        const { data: res } = await this.$http.get(`/business/ad/findById?id=${row.id}`)
         this.adForm = res
        this.imageUrl = this.adForm.image
      },
      // 删除按钮
      handleDelete (index, row) {
        const id = row.id
        // 弹框
        this.$confirm('此操作将永久删除该广告, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { data: res } = await this.$http.get(`/business/ad/delete?id=${id}`)
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 刷新页面
            this.getBrandList()
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 页大小改变
      async handleSizeChange (val) {
        this.pageSize = val
        this.getBrandList()
      },
      // 页码改变
      async handleCurrentChange (val) {
        this.currentPage = val
        this.getBrandList()
      },
      // 以下是与文件上传相关的方法
      handleAvatarSuccess (res, file) {
        // 将后台写回的图片路径赋值给imageUrl
        this.imageUrl = file.response
      },
      beforeAvatarUpload (file) {
        const isJPG = file.type === 'image/jpeg'
        // 图片大小不能大于2m
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      }
    },
    // 钩子函数
    async created () {
        this.getBrandList()
    }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
